-- Copyright (c) Huoty, All rights reserved
-- Author: Huoty <sudohuoty@gmail.com>
-- CreateTime: 2019-05-26 19:07:49

local function cache(func)
    local results = {}

    function _func(s)
        local key = string.format("k_%s_%s", func, s)
        local cached_result = results[key]
        if cached_result == nil then
            print(string.format("call function %s, and cache result, key: %s", func, key))
            local result = func(s)
            results[key] = result
            return result
        else
            print(string.format("get result from cache, key: %s", key))
            return results[key]
        end
    end

    return _func
end

local f1 = cache(function (s)
    return "hello " .. s
end)

local f2 = cache(function (s)
    return "this is " .. s
end)

print(f1("world"))
print(f1("world"))
print(f1("world"))
print(f2("apple"))
print(f2("apple"))
print(f2("apple"))
